package com.cskaoyan.wordmemorize.controller.admin;

import com.cskaoyan.wordmemorize.auth.StpKit;
import com.cskaoyan.wordmemorize.common.result.Result;
import com.cskaoyan.wordmemorize.dto.admin.AdminLoginDTO;
import com.cskaoyan.wordmemorize.request.EmployeeLoginRequest;
import com.cskaoyan.wordmemorize.service.LoginService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@Tag(name = "登录接口", description = "系统登录相关接口")
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 处理后台登录请求
     *
     * @param request            登录请求参数
     * @param httpServletRequest HTTP请求对象，用于获取IP地址
     * @return 登录结果，包含令牌
     */
    @PostMapping("admin/login")
    @Operation(summary = "后台登录", description = "后台管理员登录接口")
    public Result<AdminLoginDTO> login(@RequestBody EmployeeLoginRequest request, HttpServletRequest httpServletRequest) {
        // 调用登录服务进行登录验证，包含认证、生成Token和记录IP
        AdminLoginDTO adminLoginDTO = loginService.adminLogin(request, httpServletRequest);

        // 返回登录结果
        return Result.ok(adminLoginDTO);
    }

    /**
     * 处理后台登出请求
     *
     * @return 登出结果
     */
    @PutMapping("admin/logout")
    @Operation(summary = "后台登出", description = "后台工作人员退出登录")
    public Result<Void> logout() {
        // 注意：这里保留try-catch块是有意的
        // 这是一种特殊情况，不适合使用全局异常处理器
        try {
            // 清除当前会话
            StpKit.ADMIN.logout();

            log.info("用户成功登出");
            return Result.ok();

        } catch (Exception e) {
            // 即使登出失败也返回成功，避免前端因为登出失败而卡住。这样不会影响用户的正常使用，因为登出失败只是一个提示
            log.error("Logout failed: {}", e.getMessage(), e);
            return Result.ok();
        }
    }
}
